package com.szosen.jkzj.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.szosen.device.jianhuyi.BeneCheckDeviceHB;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.mbgy.MBGY_Main;
import com.szosen.util.SharedpreferenceUtil;
import com.szosen.util.StringUtils;

public class MainActivity extends BaseActivity {

	private BluetoothAdapter mBTAdapter;
	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// if (keyCode == KeyEvent.KEYCODE_BACK
		// && event.getAction() == KeyEvent.ACTION_DOWN) {
		// if ((System.currentTimeMillis() - exitTime) > 2000) {
		// Toast.makeText(getApplicationContext(), "再按一次退出！",
		// Toast.LENGTH_SHORT).show();
		// exitTime = System.currentTimeMillis();
		// } else {
		// System.exit(0);
		// }
		// return true;
		// }
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		super.setTitleContent("【主页】");
		String userName = SharedpreferenceUtil.getOnGovId(this, "");
		String password = SharedpreferenceUtil.getOnDoctorId(this, "");
		// if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
		// MyApplication.setUserAndPas(userName, password);
		// ToastTool.showLong(this, "连接服务器成功！");
		// } else {
		// ToastTool.showLong(this, "连接服务器失败，请设置登录！");
		// }
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();
		// niaoye niaoyeBean = new niaoye();
		// niaoyeBean.setIdCard("445555555555555555");
		// niaoyeBean.setLeu("+1");
		// niaoyeBean.setNit("+");
		// niaoyeBean.setUbg("-");
		// niaoyeBean.setPro("+1");
		// niaoyeBean.setPh("7");
		// niaoyeBean.setSg("1.025");
		// niaoyeBean.setBld("+1");
		// niaoyeBean.setKet("-");
		// niaoyeBean.setBil("+2");
		// niaoyeBean.setGlu("+-");
		// niaoyeBean.setVc("+2");
		// niaoyeBean.setTime("2016-11-18 18:10:55");
		// DBService.add(niaoyeBean);
		// xuetang xuetang = new
		// xuetang("2016-11-18 18:10:55","445555555555555555","4.2");
		// DBService.add(xuetang);
		// Intent intent = new Intent();
		// intent.setAction("android.intent.action.SEND_MULTIPLE");
		// // intent.setDataAndType(Uri.fromFile(file), "image/*");
		// intent.setType("image/*");
		// ArrayList<Uri> imageUris = new ArrayList<Uri>();
		// File f1 = new File(FileSaveUtil.getSDCardPath() + "/" + "TT",
		// "hebing.png");
		// File f2 = new File(FileSaveUtil.getSDCardPath() + "/" + "TT",
		// "niaoye.png");
		// File f3 = new File(FileSaveUtil.getSDCardPath() + "/" + "TT",
		// "saveniaoyeBitmap.png");
		// imageUris.add(Uri.fromFile(f1));
		// imageUris.add(Uri.fromFile(f2));
		// imageUris.add(Uri.fromFile(f3));
		// intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
		// startActivity(intent);
		// WebService.queryAddress(context, new StringCallback() {
		//
		// @Override
		// public void onSuccess(String arg0, Call arg1, Response arg2) {
		// System.out.println("返回的地址查询：" + arg0);
		// }
		//
		// @Override
		// public void onError(Call call1, Response response1,
		// Exception exception) {
		// super.onError(call1, response1, exception);
		// }
		// });
		setBattery();
	}

	@Override
	@SuppressLint("ResourceAsColor")
	protected void onResume() {
		super.onResume();
		if (mBTAdapter != null) {
			if (!mBTAdapter.isEnabled()) {
				mBTAdapter.enable();
			}
		}
	}

	protected void onStart() {
		super.onStart();
		sendVersion();
	};

	ImageView main_iv_battery;

	/***
	 * 电量等级12345 正在充电 6 没充电。电量耗尽
	 */
	private void setBattery() {
		main_iv_battery = (ImageView) findViewById(R.id.main_iv_battery);
		main_iv_battery.setImageResource(R.drawable.dianliang5);
		/*
		 * main_iv_battery.setOnClickListener(new View.OnClickListener() {
		 *
		 * @Override public void onClick(View v) { resIndex++;
		 * if(resIndex==ress.length){ resIndex=0; }
		 * main_iv_battery.setImageResource(ress[resIndex]); } });
		 */
		/*
		 * TimerTask task = new TimerTask() {
		 *
		 * @Override public void run() {
		 * ivhandler.obtainMessage(666).sendToTarget(); } }; Timer timer =new
		 * Timer(); timer.schedule(task, 1000, 1000);
		 */
	}

	int[] ress = new int[] { R.drawable.dianliang1, R.drawable.dianliang2,
			R.drawable.dianliang3, R.drawable.dianliang4,
			R.drawable.dianliang5, R.drawable.dianliang_chongdian_allred,
			R.drawable.dianliang_chongdian_nullred,
			R.drawable.dianliang_shandian_allred,
			R.drawable.dianliang_shandian_nullred };
	int resIndex = 0;
	public static final int READER_DATA = 3;
	private byte[] xiaweiji_version_bytes = null;
	public static String xiaweiji_version = "";
	Handler ivhandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 666) {
				resIndex++;
				if (resIndex == ress.length) {
					resIndex = 0;
				}
				main_iv_battery.setImageResource(ress[resIndex]);
			}
			switch (msg.what) {
			case READER_DATA:
				String data = (String) msg.obj;
				data = data.replaceAll(" ", "");
				// ToastTool.showLong(context, "获取数据!" + data);
				// System.out.println("MainActivity获取到usb数据：" + data);
				// 有V和.来判断是版本信息数据
				if (data.contains("2E") && data.contains("56")) {
					byte[] datas = StringUtils.HexToByteArr(data);
					xiaweiji_version_bytes = datas;
					// StringUtils.Byte2Hex(paramByte);
					if (datas.length >= 9) {
						char data0 = (char) datas[0];
						char data1 = (char) datas[1];
						char data2 = (char) datas[2];
						char data3 = (char) datas[3];
						char data4 = (char) datas[4];
						char data5 = (char) datas[5];
						char data6 = (char) datas[6];
						char data7 = (char) datas[7];
						char data8 = (char) datas[8];
						String version = "" + data0 + data1 + data2 + data3
								+ data4 + data5 + data6 + data7 + data8;
						xiaweiji_version = version;
						// 这里开始从服务器获取命令然后比对。
					}
					break;
				}
				// 01234567890123
				// EE3561XXYY55CC
				if (data.startsWith("EE3560") && data.endsWith("55CC")) {
					String battery = data.substring(6, 8);
					String state = data.substring(8, 10);
					if ("02".equals(state)) {
						// 交流电，显示插头
						main_iv_battery.setImageResource(ress[6]);
					} else {
						switch (battery) {
						case "01":
							// main_iv_battery.setImageResource(ress[0]);
							main_iv_battery
									.setImageResource(R.drawable.battery_show);
							AnimationDrawable animationDrawable = (AnimationDrawable) main_iv_battery
									.getDrawable();
							animationDrawable.start();
							// 如果是低电量1的话，使用交替显示。
							break;
						case "02":
							main_iv_battery.setImageResource(ress[1]);
							break;
						case "03":
							main_iv_battery.setImageResource(ress[2]);
							break;
						case "04":
							main_iv_battery.setImageResource(ress[3]);
							break;
						case "05":
							main_iv_battery.setImageResource(ress[4]);
							break;

						default:
							break;
						}
					}
				}
			default:
				break;
			}

		};
	};
	private BeneCheckDeviceHB beneCheckDevice;
	private UsbManager myManager;
	private static final String ACTION_USB_PERMISSION = "com.wch.wchusbdriver.USB_PERMISSION";
	Handler mGetBatteryHandler = new Handler() {
	};
	// 延时获取电池电量的时间
	Long getBatteryTimeDelay = 3000L;
	// 是否低电量的标记
	boolean isLowBattery = false;
	// 是否需要展示低电量标记。
	boolean isStartShow = false;
	Runnable mGetBatteryRunnable = new Runnable() {
		@Override
		public void run() {
			if (beneCheckDevice != null && beneCheckDevice.isConnected()) {
				// 查询电量
				byte[] command2 = new byte[] { (byte) 0xEE, 0x35, (byte) 0x60,
						0x00, (byte) 0x00, 0X55, (byte) 0XCC };
				beneCheckDevice.WriteData(command2, command2.length, 2000);
				// System.out.println("发送了一次命令： 查询电池电量");
			}
			// 3秒钟获取一次电量信息。并显示
			mGetBatteryHandler.postDelayed(mGetBatteryRunnable,
					getBatteryTimeDelay);

		}
	};

	// 主线程执行任务太多
	// 电量闪烁显示的任务runnable

	public void sendVersion() {
		// System.out.println("oncreate调用了方法。sendVersionAndBattery");
		if (myManager == null) {
			myManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		}
		if (beneCheckDevice == null || !beneCheckDevice.isConnected()) {
			beneCheckDevice = new BeneCheckDeviceHB(myManager,
					MainActivity.this, ACTION_USB_PERMISSION, ivhandler);
		}
		// 获取一次电量信息。并显示
		mGetBatteryHandler.postDelayed(mGetBatteryRunnable, 0);
		isLowBattery = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		mGetBatteryHandler.removeCallbacks(mGetBatteryRunnable);
		if (beneCheckDevice != null) {
			if (beneCheckDevice.isConnected()) {
				beneCheckDevice.CloseDevice();
			}
		}
		// System.out.println("onPause调用了方法。此处关闭了设备的连接");
	}

	protected void onStop() {
		super.onStop();
		// System.out.println("onStop调用了方法。sendVersionAndBattery");
		if (beneCheckDevice != null) {
			if (beneCheckDevice.isConnected()) {
				beneCheckDevice.CloseDevice();
			}
		}
		isLowBattery = false;
		isStartShow = false;

	};

	public void jumpTo(View view) {
		int id = view.getId();
		Intent intent = null;
		switch (id) {
		case R.id.health_files_button: // 健康档案
			intent = new Intent(this, UserListActivity.class);
			intent.putExtra(BaseActivity.ACTIVITY_FLAG,
					BaseActivity.ACTIVITY_FLAG_JKDA);
			break;
		case R.id.health_checkup_button: // 健康体检
			intent = new Intent(this, UserListActivity.class);
			intent.putExtra(BaseActivity.ACTIVITY_FLAG,
					BaseActivity.ACTIVITY_FLAG_JKTJ);
			break;
		case R.id.chronicdisease_button_button: // 慢病干预
			// intent = new Intent(this, UserListActivity.class);
			intent = new Intent(this, MBGY_Main.class);
			intent.putExtra(BaseActivity.ACTIVITY_FLAG,
					BaseActivity.ACTIVITY_FLAG_MBGY);
			break;
		case R.id.activity_main_ggws_btn:// 公共卫生
			intent = new Intent(this, UserListActivity.class);
			intent.putExtra(BaseActivity.ACTIVITY_FLAG,
					BaseActivity.ACTIVITY_FLAG_GGWS);
			break;
		default:
			return;
		}
		if (intent != null) {
			startActivity(intent);
		}
	}

	public void toSetting(View view) {
		Intent intent = new Intent(this, SettingActivity.class);
		// Intent intent = new Intent(this, JiBingActivity.class);
		startActivity(intent);
	}
}
